import React, { useState, useEffect, useRef } from 'react'
import { createPortal } from 'react-dom'
import { Sparkles, Scissors, BookOpen, Languages, CheckCircle, Palette, FileText, PenTool, Loader2, AlertCircle } from 'lucide-react'

interface AIContextMenuProps {
  position: { x: number; y: number }
  selectedText: string
  onAction: (action: string, text: string, options?: { stream?: boolean }) => Promise<string>
  onClose: () => void
  onStreamChunk?: (chunk: string) => void
  onStreamComplete?: (result: string) => void
  onStreamError?: (error: string) => void
}

interface AIAction {
  id: string
  label: string
  icon: React.ReactNode
  description?: string
}

const AIContextMenu: React.FC<AIContextMenuProps> = ({
  position,
  selectedText,
  onAction,
  onClose,
  onStreamChunk,
  onStreamComplete,
  onStreamError
}) => {
  const menuRef = useRef<HTMLDivElement>(null)
  const [isLoading, setIsLoading] = useState<string | null>(null)
  const [error, setError] = useState<string>('')
  const [streamResult, setStreamResult] = useState<string>('')

  const actions: AIAction[] = [
    { id: 'polish', label: '润色', icon: <Sparkles className="w-4 h-4" />, description: '优化表达，使其更流畅专业' },
    { id: 'shorten', label: '缩写', icon: <Scissors className="w-4 h-4" />, description: '提炼核心观点，压缩文本' },
    { id: 'expand', label: '扩写', icon: <BookOpen className="w-4 h-4" />, description: '丰富内容，增加细节和深度' },
    { id: 'translate', label: '翻译', icon: <Languages className="w-4 h-4" />, description: '翻译成目标语言' },
    { id: 'fix-grammar', label: '修正语法', icon: <CheckCircle className="w-4 h-4" />, description: '修复拼写和语法错误' },
    { id: 'change-tone', label: '切换语气', icon: <Palette className="w-4 h-4" />, description: '改变文本语气' },
    { id: 'summarize', label: '总结', icon: <FileText className="w-4 h-4" />, description: '总结内容要点' },
    { id: 'continue-writing', label: '续写', icon: <PenTool className="w-4 h-4" />, description: '智能续写内容' }
  ]

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (menuRef.current && !menuRef.current.contains(event.target as Node)) {
        onClose()
      }
    }

    const handleEscape = (event: KeyboardEvent) => {
      if (event.key === 'Escape') {
        onClose()
      }
    }

    document.addEventListener('mousedown', handleClickOutside)
    document.addEventListener('keydown', handleEscape)

    return () => {
      document.removeEventListener('mousedown', handleClickOutside)
      document.removeEventListener('keydown', handleEscape)
    }
  }, [onClose])

  // Position adjustment to keep menu within viewport
  const adjustPosition = () => {
    const adjustedPosition = { ...position }
    const menuWidth = 280 // Actual width from min-w-[280px]
    const menuItemHeight = 44 // Approximate height of each menu item
    const menuHeight = actions.length * menuItemHeight

    // Check if menu would go off the right edge
    if (position.x + menuWidth > window.innerWidth) {
      adjustedPosition.x = window.innerWidth - menuWidth - 10
    }

    // Check if menu would go off the bottom edge
    if (position.y + menuHeight > window.innerHeight) {
      // Position menu above the selected text instead
      adjustedPosition.y = position.y - menuHeight - 10
    }

    // Ensure menu doesn't go off the left edge
    if (adjustedPosition.x < 10) adjustedPosition.x = 10

    // Ensure menu doesn't go off the top edge
    if (adjustedPosition.y < 10) adjustedPosition.y = 10

    return adjustedPosition
  }

  const handleAction = async (actionId: string) => {
    setIsLoading(actionId)
    setError('')
    setStreamResult('')

    // Check if streaming is enabled in settings
    const settings = await window.electronAPI.getSettings()
    const useStreaming = settings.ai?.streaming !== false // Default to true

    try {
      
      if (useStreaming && onStreamChunk) {
        // Use streaming for better UX
        const requestId = `ai-${Date.now()}`
        
        // Set up streaming listeners
        const unsubscribeChunk = window.electronAPI.onAIStreamChunk?.((data) => {
          if (data.requestId === requestId) {
            setStreamResult(prev => prev + data.chunk)
            onStreamChunk(data.chunk)
          }
        })
        
        const unsubscribeEnd = window.electronAPI.onAIStreamEnd?.((data) => {
          if (data.requestId === requestId) {
            setIsLoading(null)
            onStreamComplete?.(data.result || streamResult)
            onClose()
          }
        })
        
        const unsubscribeError = window.electronAPI.onAIStreamError?.((data) => {
          if (data.requestId === requestId) {
            setError(data.error)
            setIsLoading(null)
            onStreamError?.(data.error)
          }
        })

        try {
          await window.electronAPI.streamAI(actionId, selectedText, {}, requestId)
        } finally {
          // Cleanup listeners
          unsubscribeChunk?.()
          unsubscribeEnd?.()
          unsubscribeError?.()
        }
      } else {
        // Fallback to regular invoke
        const result = await onAction(actionId, selectedText)
        onStreamComplete?.(result)
        onClose()
      }
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : 'AI操作失败'
      setError(errorMessage)
      onStreamError?.(errorMessage)
      console.error('AI action failed:', error)
    } finally {
      if (!useStreaming || !onStreamChunk) {
        setIsLoading(null)
      }
    }
  }

  const finalPosition = adjustPosition()

  return createPortal(
    <div
      ref={menuRef}
      className="fixed z-50 bg-white/95 dark:bg-gray-900/95 backdrop-blur-sm border border-gray-200/60 dark:border-gray-700/60 rounded-xl shadow-2xl py-2 min-w-[320px] animate-in fade-in-0 zoom-in-95 duration-200"
      style={{
        left: `${finalPosition.x}px`,
        top: `${finalPosition.y}px`,
      }}
    >
      {/* Streaming Preview */}
      {(streamResult || error) && (
        <div className="px-3 py-2 border-b border-gray-200 dark:border-gray-700">
          {error ? (
            <div className="flex items-center gap-2 text-red-600 dark:text-red-400">
              <AlertCircle className="w-4 h-4 flex-shrink-0" />
              <span className="text-sm">{error}</span>
            </div>
          ) : (
            <div>
              <div className="text-xs text-gray-500 dark:text-gray-400 mb-1">AI 正在处理中...</div>
              <div className="text-sm text-gray-700 dark:text-gray-300 max-h-20 overflow-y-auto bg-gray-50 dark:bg-gray-800 rounded p-2">
                {streamResult}
              </div>
            </div>
          )}
        </div>
      )}

      {/* Actions */}
      <div className="px-1">
        {actions.map((action) => (
          <button
            key={action.id}
            onClick={() => handleAction(action.id)}
            disabled={isLoading !== null}
            className="w-full px-3 py-2.5 text-left hover:bg-gray-100 dark:hover:bg-gray-800 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200 flex items-center gap-3 group rounded-lg"
            title={action.description}
          >
            <div className="flex-shrink-0 w-8 h-8 bg-gray-100 dark:bg-gray-700 group-hover:bg-blue-100 dark:group-hover:bg-blue-900/30 rounded-lg flex items-center justify-center transition-colors">
              <div className="text-gray-600 dark:text-gray-400 group-hover:text-blue-600 dark:group-hover:text-blue-400 transition-colors">
                {action.icon}
              </div>
            </div>
            <div className="flex-1 min-w-0">
              <div className="text-sm font-medium text-gray-900 dark:text-gray-100 group-hover:text-blue-600 dark:group-hover:text-blue-400 transition-colors">
                {action.label}
              </div>
              <div className="text-xs text-gray-500 dark:text-gray-400 truncate">
                {action.description}
              </div>
            </div>
            {isLoading === action.id && (
              <div className="flex-shrink-0">
                <Loader2 className="w-4 h-4 text-blue-500 animate-spin" />
              </div>
            )}
          </button>
        ))}
      </div>
    </div>,
    document.body
  )
}

export default AIContextMenu